<?php


namespace App\Http\Controllers\Admin;


use App\Http\Controllers\Controller;
use App\Services\MemberService;
use EasyWeChat\Factory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class CustomerServiceController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth:admin');
    }

    public function showLevel()
    {
        return view('admin.customer_service.level');
    }

    /**
     * 等级列表
     * @return \Illuminate\Http\JsonResponse
     */
    public function getLevelList()
    {
        $levelList = DB::table('customer_service_level')->get();
        $userLevelMap = $list = DB::table('user_level')->pluck('title', 'id');
        foreach ($levelList as &$level) {
            if ($level->reward) {
                $level->reward = json_decode($level->reward);
                $level->start_vip_title = $userLevelMap[$level->start_vip] ?? '-';
                $level->end_vip_title = $userLevelMap[$level->end_vip] ?? '-';
            }
        }
        return successResp($levelList);
    }

    /**
     * 保存客服等级
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Validation\ValidationException
     */
    public function saveLevel(Request $request)
    {
        //验证表单
        $this->validate($request, [
            'id' => [],
            'name' => ['required'],
            'reward' => ['required'],
            'start_vip' => ['required','numeric'],
            'end_vip' => ['required','numeric'],
        ]);
        $data = [
            'name' => $request->name,
            'reward' => json_encode($request->reward),
            'start_vip' => $request->start_vip,
            'end_vip' => $request->end_vip,
        ];
        if ($request->id) {
            $re = DB::table('customer_service_level')
                ->where('id',$request->id)
                ->update($data);
        } else {
            $re = DB::table('customer_service_level')->insert($data);
        }
        if ($re) {
            return successResp($data);
        }
        return errorResp('保存失败');
    }

    public function showService()
    {
        return view('admin.customer_service.index');
    }

    /**
     * 客服列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getServiceList(Request $request)
    {
        $list = DB::table('customer_service')
            ->where(function ($query) {
                if (@$_GET['level_id']) {
                    $query->where('level_id', @$_GET['level_id']);
                }
                if (@$_GET['nickname']) {
                    $query->where('nickname', @$_GET['nickname']);
                }
            })
            ->orderBy('id', 'desc')
            ->get();
        $levelMap = DB::table('customer_service_level')->pluck('name', 'id');
        foreach ($list as &$v) {
            $v->level_name = $levelMap[$v->level_id] ?? '';
        }
        return successResp($list);
    }

    /**
     * 保存客服
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Validation\ValidationException
     */
    public function saveService(Request $request)
    {
        //验证表单
        $this->validate($request, [
            'id' => [],
            'nickname' => ['required'],
            'level_id' => ['required','numeric'],
        ]);
        $adminData = [
            'username' => $request->nickname,
        ];
        $data = [
            'nickname' => $request->nickname,
            'level_id' => $request->level_id,
        ];
        if ($request->id) {
            $re = DB::table('customer_service')
                ->where('id',$request->id)
                ->update($data);
            $re = DB::table('admins')
                ->where('id',$request->id)
                ->update($adminData);
        } else {
            $adminData['role'] = 2;
            $adminData['password'] = Hash::make('123456');
            $adminId = DB::table('admins')->insertGetId($adminData);
            $data['id'] = $adminId;
            $re = DB::table('customer_service')->insert($data);
        }
        if ($re) {
            return successResp($data);
        }
        return errorResp('保存失败');
    }

    /**
     * 设置密码
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Validation\ValidationException
     */
    public function setPassword(Request $request)
    {
        //验证表单
        $this->validate($request, [
            'id' => ['required'],
            'password' => ['required'],
        ]);
        $log = DB::table('customer_service')->find($request->id);
        if (!$log) {
            return errorResp('记录错误');
        }
        $re = DB::table('admins')
            ->where('id',$request->id)
            ->update(['password' => Hash::make($request->password)]);
        if ($re) {
            return successResp('修改成功');
        }
        return errorResp('修改失败');
    }

    /**
     * 绑定客服
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Validation\ValidationException
     */
    public function bindService(Request $request)
    {
        $this->validate($request, [
            'unionid' => ['required'],
            'service_id' => ['required','numeric']
        ]);
        try {
            $id = MemberService::bindCustomService($request->unionid, $request->service_id, 2);
            return successResp($id);
        }catch (\Exception $e) {
            return errorResp($e->getMessage());
        }
    }

    /**
     * 获取用户绑定二维码
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getServiceBindCode(Request $request)
    {
        $uid = $request->get('admin_id', 0);
        // 2是客服
        if (Auth::user()->role === 2) {
            $uid = Auth::user()->id;
        }
        header("Access-Control-Allow-Origin:*");
        $config = config('wechat');
        $app = Factory::officialAccount($config);
        $result = $app->qrcode->temporary("ctmSer_{$uid}", 86400*7);
        return successResp($result);
    }

    /**
     * 用户升级页面
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function showUserUpgrade()
    {

        return view('admin.customer_service.user_upgrade', ['adminRole' => Auth::user()->role]);
    }

    /**
     * 获取用户升级记录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserUpgradeLog(Request $request)
    {
        $startTime = date('Y-01-01 00:00:00');
        $endTime = date('Y-m-d H:i:s');
        if ($request->start) {
            $startTime = "{$request->start} 00:00:00";
        }
        if ($request->end) {
            $endTime = "{$request->end} 23:59:59";
        }
        $w = [
            ['create_time', '>=', $startTime],
            ['create_time', '<=', $endTime],
        ];
        if (@$_GET['unionid']) {
            $w[] = ['unionid', '=', $_GET['unionid']];
        }
        // 2是客服
        if (Auth::user()->role === 2) {
            $w[] = ['customer_service_id', '=', Auth::user()->id];
        } else {
            if (@$_GET['customer_service_id']) {
                $w = ['customer_service_id', '=', $_GET['customer_service_id']];
            }
        }
        $levelMap = DB::table('user_level')->pluck('title', 'id');
        $kfMap = DB::table('customer_service')->pluck('nickname', 'id');
        $list = DB::table('user_upgrade_log')
            ->where($w)
            ->orderBy('id', 'desc')
            ->paginate(10);
        foreach ($list as &$value) {
            $value->old_title = $levelMap[$value->old_level] ?? '';
            $value->new_title = $levelMap[$value->new_level] ?? '';
            $value->kf_name = $kfMap[$value->customer_service_id] ?? '';
        }
        $totalReward = DB::table('user_upgrade_log')
            ->where($w)
            ->sum('reward');
        return successResp(['list' => $list, 'total_reward'=>$totalReward]);
    }
}
